/**
 * @author zqd	差旅小组
 *
 * 下午07:38:17
 */
package com.cbts.util;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;

/**
 * 解决json死循环
 */
public class ObjectJsonValueProcessor implements JsonValueProcessor{

	//需要留下的字段数组
	private String[] properties;
	
	//需要做处理的复杂属性类型
	private Class<?> clazz;
	
	/**
	 * 构造函数
	 * @param properties
	 * @param clazz
	 */
	public ObjectJsonValueProcessor(String[] properties,Class<?> clazz){
		this.properties=properties;
		this.clazz=clazz;
	}
	
	/* 
	 * @see net.sf.json.processors.JsonValueProcessor#processArrayValue(java.lang.Object, net.sf.json.JsonConfig)
	 */
	public Object processArrayValue(Object value, JsonConfig config) {
		// zqd 下午07:39:51
		return "";
	}

	/* 
	 * @see net.sf.json.processors.JsonValueProcessor#processObjectValue(java.lang.String, java.lang.Object, net.sf.json.JsonConfig)
	 */
	public Object processObjectValue(String key, Object value, JsonConfig config) {
		// zqd 下午07:39:51
		PropertyDescriptor pd=null;
		Method method=null;
		StringBuffer json=new StringBuffer("{");
		try{
			for(int i=0;i<properties.length;i++){
				String v = "";
				pd=new PropertyDescriptor(properties[i],clazz);
				method=pd.getReadMethod();
				if(value == null)
					v="";
				else
					v=String.valueOf(method.invoke(value));
				json.append("'"+properties[i]+"':'"+v+"'");
	            json.append(i != properties.length-1?",":"");
			}
			json.append("}");
		}catch(Exception e){
			e.printStackTrace();
		}
		return JSONObject.fromObject(json.toString());
	}

}
